package netty.time;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;

import java.util.Date;

/**
 * @author zengjian
 * @create 2018-04-17 11:34
 * @since 1.0.0
 */
public class TimeServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        // 服务启动类
        ServerBootstrap b = new ServerBootstrap();
        try {
            // 分两个线程组
            b.group(bossGroup, workGroup)
                    // 通道
                    .channel(NioServerSocketChannel.class)
                    //  设置参数
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 业务类型
                    .childHandler(new ChildChannerHandler());
            System.out.println("templates 服务端启动..");
            // 类似于future返回绑定的结果，阻塞
            ChannelFuture f = b.bind(8080).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    private static class ChildChannerHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            // 增加前两条用于解决粘包拆包现象
            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
            // socketChannel.pipeline().addLast(new StringDecoder());
            socketChannel.pipeline().addLast(new TimeServerHandler());
        }
    }

    private static class TimeServerHandler extends ChannelInboundHandlerAdapter {

        private int count = 0;

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = new String(req, "utf-8");
            System.out.println("server revice req:" + body + "; 第" + ++count + "请求");
            String currentTime = body.equalsIgnoreCase("QUERY TIME ORDER") ? new Date().toString() : "BAD QUERY";
            currentTime = currentTime + System.getProperty("line.separator");
            ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
            ctx.write(resp);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
}
